import { NgFor } from '@angular/common';
import { Component, Input } from '@angular/core';
import { NzGridModule } from 'ng-zorro-antd/grid';
import { NzLayoutModule } from 'ng-zorro-antd/layout';
import { NzModalModule } from 'ng-zorro-antd/modal';
import { Column } from '../../type';

type Callback<T> = (selectedFields: (keyof T)[]) => void;

@Component({
  selector: 'app-field-selector',
  standalone: true,
  imports: [NzModalModule, NgFor, NzLayoutModule, NzGridModule],
  templateUrl: './field-selector.component.html',
  styleUrl: './field-selector.component.css'
})
export class FieldSelectorComponent<T> {

  selectedFields: (keyof T)[] = [];

  visible = false;
  // fields: (keyof T)[] = [];
  private onConfirm: Callback<T> | null = null;

  @Input() columns: Column<T>[] = [];
  // @Input() get fields() {
  //   return this._fields;
  // }
  // set fields(value) {
  //   value = value || [];
  //   this._fields = value;
  // }

  // @Input() get visible() {
  //   return this._visible;
  // }
  // set visible(value) {
  //   if (value) {
  //     this.selectedFields = [...this.fields];
  //   }
  //   else {
  //     this.selectedFields = [];
  //   }
  //   this._visible = value;
  // }

  close() {
    while (this.selectedFields.length > 0) {
      this.selectedFields.pop();
    }
    this.visible = false;
  }

  confirm() {
    // while (this.fields.length > 0) {
    //   this.fields.pop();
    // }
    // this.fields.push(...this.selectedFields);
    this.visible = false;
    if (this.onConfirm) {
      this.onConfirm(this.selectedFields);
    }
    this.close();
  }

  onFieldChanged(event: Event, field: keyof T) {
    let input = event.target as HTMLInputElement;
    if (input.checked) {
      this.selectedFields.push(field);
    }
    else {
      if (this.selectedFields.length == 1) {
        //TODO: 至少保留一项 显示错误信息
        return;
      }
      this.selectedFields = this.selectedFields.filter(O => O != field);
    }
  }

  show(fields: (keyof T)[], onConfirm?: Callback<T>) {
    this.selectedFields.push(...fields);
    this.visible = true;
    this.onConfirm = onConfirm || null;
  }
}
